//
//  XQLocationManager.m
//  JoinPeso
//
//  Created by 小琦 on 2024/12/4.
//

#import "XQLocationManager.h"

@interface XQLocationManager()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation XQLocationManager

+ (instancetype)manager {
    static XQLocationManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        manager.locationManager = [[CLLocationManager alloc] init];
        manager.locationManager.delegate = manager;
        [manager.locationManager requestAlwaysAuthorization];
        manager.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        manager.locationManager.distanceFilter = 0.01;
    });
    return manager;
}

- (void)startLocation {
    [self.locationManager stopUpdatingLocation];
    [self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

 //地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [manager stopUpdatingLocation];
            
    if (locations.count) {
                                
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray *array, NSError *error) {
            if (error) {
                return;
            }
            if (array.count) {
                [XQToolManager manager].placemark = [array firstObject];
                
            }
            
            [XQToolManager manager].location = locations.lastObject;
     
            [XQGoogleMarket reportLocation];
        }];
    }
}

/// 定位失败回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locationError, error: %@",error);
    switch([error code]) {
        case kCLErrorDenied: { // 用户禁止了定位权限
            
        } break;
        default: break;
    }
}


@end
